import axios  from "axios";
import type { AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
import store from "@/store";
import router from "@/router";

interface ExtrasParams {
    loading?: boolean;
    needToken?: boolean;
    header?: any;
}

export const host = import.meta.env.VITE_API_HOST;

const instance = axios.create({
    //baseURL: 'https://bigscreen-manage.lecarecloud.com', //prd
    baseURL: host,//'http://47.102.155.180:61610', //test
    //baseURL: 'http://192.168.1.8:64323',
    timeout: 30000
});

//instance.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';

export default function<T>(method: string, url: string, data?: any, extras?:ExtrasParams = {}): Promise<T>{
    return new Promise((resolve,reject)=>{
        const config: any = {
            url,
            method,
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
                "token": store.state.permission.token
            },
            transformRequest: [function (request, headers) {
                return request;
            }],
            transformResponse: [function (response) {
                return response;
            }]
        }
        if(method == 'get' || method == 'GET'){
            config.params = data;
        }else{
            config.data = JSON.stringify(data||{});
        }
        instance(config).then((response: AxiosResponse)=>{
            const json = JSON.parse(response.data);
            if(json.code == 0){
                resolve(json)
            }else{
                if(json.code == 401){
                    store.dispatch('permission/setLogin',false);
                    store.dispatch('permission/setToken','');
                    router.push('/login')
                }
                ElMessage({
                    showClose: true,
                    message: json.message,
                    type: 'error',
                })
                reject(json)
            }
            
        }).catch(err=>{
            const errorData = JSON.parse(err.response.data);
            ElMessage({
                showClose: true,
                message: errorData.message,
                type: 'error',
              })
            reject(err)
        })
    })
}